﻿

using IoTClient;
using IotClientService.Models.Lg;
using IotClientService.Services;
using IotContract.Dtos.Clients.Equips;
using IotContract.Dtos.Servers;
using IotContract.Enums;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using XT.Common.Config;
using XT.Common.Extensions;
using XT.Common.Services;

namespace IotClientService.Handles.lgs;
public abstract class LgHandleBase
{
    public  event EventHandler<(LgMsgInfo,LgHkEquipDto)> SendMsgEvent;
    private ILogService _logService;

    public ILgApiService Api { get; set; }
    public LgHandleBase(ILgApiService lgCallApiService)
    {
        Api = lgCallApiService;
    }
    #region 配置

    //modGlobal.gnUnitCNT = int.Parse(ConfigurationManager.AppSettings["UnitCnt"] ?? "0");
    //modGlobal.gsUnitID = ConfigurationManager.AppSettings["UnitID"];
    //modGlobal.gsUnitID2 = ConfigurationManager.AppSettings["UnitID2"];
    //modGlobal.gsUnitID3 = ConfigurationManager.AppSettings["UnitID3"];
    //modGlobal.gtConfig.nErrLevel = int.Parse(ConfigurationManager.AppSettings["LogLevel"] ?? "5");
    //modGlobal.gtConfig.nTop = int.Parse(ConfigurationManager.AppSettings["TopPosition"] ?? "20");
    //modGlobal.gtConfig.nLeft = int.Parse(ConfigurationManager.AppSettings["LeftPosition"] ?? "20");
    //modGlobal.gsLineID = ConfigurationManager.AppSettings["LineID"];
    //modGlobal.gnPLCCNT = int.Parse(ConfigurationManager.AppSettings["PLCCNT"] ?? "0");
    //modGlobal.gsAppVersion = ConfigurationManager.AppSettings["Version"];
    //modGlobal.gnOrderMaxCount = int.Parse(ConfigurationManager.AppSettings["OrderMaxCount"] ?? "40");
    //modGlobal.gtConfig.sObjID = $"{modGlobal.gsLineID}{modGlobal.gsEqpTypeID}{modGlobal.gsUnitID}";

    //// Check if any of the required settings are missing or empty
    //if (string.IsNullOrEmpty(modGlobal.gsLineID) || string.IsNullOrEmpty(modGlobal.gsEqpTypeID) || string.IsNullOrEmpty(modGlobal.gsUnitID))
    //{
    //    MessageBox.Show("Check Equipment information (CONFIGURATION)");
    //    psSetEqpRegistry();
    //}
    //else
    //{
    //    result = true;
    //}

    //return result;

    #endregion
    /// <summary>
    /// 设备类型
    /// </summary>
    public abstract IotEquipType EquipType { get; set; }
    /// <summary>
    /// 设备
    /// </summary>
    public LgHkEquipDto Equip { get; set; }
    // 设备ID ,用其它变量进行判断
    public string LgEquipTypeID { get; set; }
    // 线体ID
    public string LgLineID { get; set; }

   
    StringBuilder messageBuilder = new StringBuilder();
    public void ParseData(LgHkEquipDto equip,CancellationToken token)
    {
        Equip = equip;
        // 将byte数组转换为Base64字符串
        string base64String = Convert.ToBase64String(equip.Data);

        // 将Base64字符串转换回byte数组
        equip.Data = Convert.FromBase64String(base64String);
        foreach (var item in equip.Data)
        {
            switch (item)
            {
                case 2:
                    // 如果item是2，跳过当前迭代。
                    break;
                case 3:
                    // 如果item是3，验证消息，如果有效则处理。
                    string message = messageBuilder.ToString();
                    if (ValidateMsg(message))
                    {
                        Task.Factory.StartNew(async (o) =>
                        {
                            await HandleData(o.ToString());
                        }, message, token);
                    }
                    // 重置StringBuilder以用于下一条消息。
                    messageBuilder.Clear();
                    break;
                default:
                    // 将item转换为char并添加到StringBuilder。
                    messageBuilder.Append(Convert.ToChar(item));
                    break;
            }
        }

    }
    /// <summary>
    /// 处理数据
    /// </summary>
    /// <param name="message"></param>
    public async Task HandleData(string message,LgHkEquipDto lgHkEquipDto=null)
    {
        if (lgHkEquipDto != null)
        {
            Equip = lgHkEquipDto;

        }
        message = message.Replace("\0","");
        message = message.Replace("\u0002", "");
        message = message.Replace("\u002B", " ").Replace("\u002D", "-");
      
        if (message.Length < 12) return;
        var command = message.Substring(9, 3);

        Api.LogMessage($"Rceive:{Equip.Num},{command}: {message}");

        // 回应message 1 有 0 无
        if (message.Length>=18)
        { 
            LgMsgInfo msg = new LgMsgInfo();
            msg.SeqNo = message.Substring(12, 5);
            // 1810116
            msg.ObjID = message.Substring(1, 7);
            msg.Command = message.Substring(9, 3);
            msg.Message = message;
           
            Equip.ReadTime = DateTime.Now;
            await HandleMsg(msg);
        }

        



    }
    /// <summary>
    /// 处理信息
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public abstract  Task<bool> HandleMsg(LgMsgInfo msg);
    /// <summary>
    /// 验证消息
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    private bool ValidateMsg(string msg)
    {
        if(msg.Length < 18)
        {
            return false;
        }

        //if (msg.Substring(2, 1) != LgEquipTypeID)
        //{
        //    return false;
        //}

        //if(msg.Substring(1,1)!=LgLineID)
        //{
        //    return false; 
        //}

        return true;            
    }

    /// <summary>
    /// 触发发送消息
    /// </summary>
    /// <param name="msg"></param>
    public void InvokeSend(LgMsgInfo msg)
    {
        SendMsgEvent?.Invoke(this, (msg,Equip));
    }

    /// <summary>
    /// 组装消息
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public string AssambleMsg(LgMsgInfo e)
    {
        e.SeqNo = "00001";
        if (e.ObjID.IsNullOrEmpty())
        {
            e.ObjID = "1A30103";
        }
        string msg = $"{e.Direction}{e.ObjID}{e.HasMsg}{e.Command}{e.SeqNo}{e.BoxId}{e.Body}";
        var checkSum = e.MakeCheckSum(msg);
        var send = $"\u0002{msg}{checkSum}\u0003";
        return send ;
    }

    /// <summary>
    /// 同步时间
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public bool SyncTime(LgMsgInfo e)
    {
        e.HasMsg = 1;
        e.Command = "998";
        e.IsSend = true;
        e.Body = DateTime.Now.ToString("yyyyMMddHHmmss");
        InvokeSend(e);
        return true;
    }
    /// <summary>
    /// <param name="e"></param>
    /// 同步状态 FMS 要求设备报告当前状态，待机，运行，异常，有无通电，自动，手动等
    /// </summary>
    /// <returns></returns>
    public bool SyncStatus(LgMsgInfo e)
    {
       
        e.Command = "909";
        e.IsSend = true;
        InvokeSend(e);
        return true;
    }
    /// <summary>
    /// 同步Mode  0:Control Model   1:Maintenance Mode
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public bool SyncMode(LgMsgInfo e)
    {
        e.HasMsg = 1;
        e.Command = "921";
        e.IsSend = true;
        InvokeSend(e);
        return true;
    }
    /// <summary>
    /// 停止作业,充放电机
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public bool Stop(LgMsgInfo e)
    {
        
        e.HasMsg = 1;
        e.Command = "129";
        e.IsSend = true;
        // E:现工程作业结束 P:现工程暂停
        e.Body = e.Body;
        InvokeSend(e);
        return true;
    }
    /// <summary>
    /// 作业再开始
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public bool ReStart(LgMsgInfo e)
    {
        e.BoxId = 1;
        e.HasMsg = 1;
        e.Command = "133";
        e.IsSend = true;
        // E:从停止的站点开始连续作业 P:停止工程再作业(Recipe邀请)
        e.Body = e.Body;
        InvokeSend(e);
        return true;
    }
    /// <summary>
    /// 最终状态
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public bool FinalStatus(LgMsgInfo e)
    {
        e.BoxId = 1;
        e.Command = "135";
        e.IsSend = true;
        InvokeSend(e);
        return true;
    }


    #region 通用报告
    /// <summary>
    /// 错误处理
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    protected async Task Handle981(LgMsgInfo msg, string replyCmd)
    {
        

        //Command为981，表示设备上传的981
        if(msg.Command == "981")
        {
            //设备上传981，不回应设备，只做记录
            // 1:Unknown Command  2:Size Error  3:Checksum Error
            string ret = msg.Message.Substring(18, 1);
            Equip.Remark = $"command error:{ret}";
        }
        else//其他命令，表示其他命令异常，主动向设备发981
        {
            msg.Command = "981";
            //返回1：Unknown Command，调用FMS接口异常和未识别的命令都用1表示，
            msg.Body = "1";
            msg.IsSend = true;
            InvokeSend(msg);
        }
    }
    /// <summary>
    /// 设备trouble报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    protected async Task Handle985(LgMsgInfo msg, string replyCmd)
    {
        // TroubleId 供应商定义 （800-899）
        string troubleId = msg.Message.Substring(18, 4);
        Equip.Remark = $"error code:{troubleId}";
        InvokeSend(msg);

    }

    /// <summary>
    /// 设备状态报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    protected async Task Handle913(LgMsgInfo msg, string replyCmd)
    {
        // 设备状态 R:Running  I:Idle  T:Trouble  P:Power on  O:Power off
        string status = msg.Message.Substring(18, 1);

        Equip.EquipStatus = status;
        

        InvokeSend(msg);
    }
    /// <summary>
    /// 作业mode报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    protected async Task Handle917(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // 设备mode 0:control   1:maintenance
        string mode = msg.Message.Substring(18, 1);

        Equip.Mode = mode;

        
        sendMsg.Body = "0";
        sendMsg.IsSend = true;


        #region 验证长度，发送 981 2或3

        #endregion

        InvokeSend(sendMsg);
    }

    /// <summary>
    /// 设备状态报告指示回应
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    protected async Task Handle910(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };

        // 设备状态 R:Running  I:Idle  T:Trouble  P:Power on  O:Power off
        string status = msg.Message.Substring(18, 1);
        // 作业模式 0:Control Model  1:Maintenance Mode
        string mode = msg.Message.Substring(19, 1);


        if (Equip.EquipType == IotEquipType.OCV.ToString() || Equip.EquipType==IotEquipType.FMT.ToString())
        {
            // 托盘有无  0:无  1:有
            string isExist = msg.Message.Substring(20, 1);


            if (isExist=="0")
            {
                Equip.Obj = "";
            }
        }
       




        Equip.EquipStatus = status;
        Equip.Mode = mode;


        InvokeSend(sendMsg);



    }
    /// <summary>
    /// 通信状态报告邀请
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    protected async Task Handle925(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };



        sendMsg.Body = "0";
        sendMsg.IsSend = true;


        #region 验证长度，发送 981 2或3

        #endregion

        InvokeSend(sendMsg);
    }
    /// <summary>
    ///  // 通信状态报告回应
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    protected async Task Handle926(LgMsgInfo msg, string replyCmd)
    {
        // 通信状态 0:online  1:offline
        var status = msg.Message.Substring(18, 1);
        Equip.Remark = $"heart:{status}";
        InvokeSend(msg);
    }

    /// <summary>
    /// 设置时间回应
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    protected async Task Handle999(LgMsgInfo msg, string replyCmd)
    {
        // 1:0k  2:ng
        string ret = msg.Message.Substring(18, 1);

        InvokeSend(msg);
    }
    #endregion









}
